﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ImbaTracker.Models;
using ImbaTracker.Content;

namespace ImbaTracker.Controllers {

    [HandleError]
    public class AccountController : Controller {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext) {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn() {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl) {
            if (ModelState.IsValid) {
                if (MembershipService.ValidateUser(model.UserName, model.Password)) {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl)) {
                        return Redirect(returnUrl);
                    } else {
                        return RedirectToAction("Index", "Home");
                    }
                } else {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff() {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register() {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model) {
            if (ModelState.IsValid) {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Login, model.Name, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success) {
                    FormsService.SignIn(model.Login, false /* createPersistentCookie */);
                    var db = new ImbaDBEntities();
                    var users = db.Users;
                    db.AddToUsers(new User() { Login = model.Login, Name = model.Name });
                    db.SaveChanges();

                    return RedirectToAction("Index", "Home");
                } else {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword() {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model) {
            if (ModelState.IsValid) {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) {
                    return RedirectToAction("ChangePasswordSuccess");
                } else {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************
        [Authorize]
        public ActionResult ChangePasswordSuccess() {
            return View();
        }

        // **************************************
        // URL: /Account/
        // **************************************

        ImbaDBEntities db = new ImbaDBEntities();
        [Authorize]
        public ActionResult Index() {
            var accounts = from u in db.Users select u;
            return View(accounts.ToList());
        }

        // **************************************
        // URL: /Account/Create/
        // **************************************
        [Authorize]
        public ActionResult Create() {
            return View();
        }

        [HttpPost]
        public ActionResult Create(User newAccount) {

            if (ModelState.IsValid) {
                db.AddToUsers(newAccount);
                db.SaveChanges();

                return RedirectToAction("Index");
            } else {
                return View(newAccount);
            }
        }

        public ActionResult Delete(User oldAccount) {
            var user = db.Users.FirstOrDefault(u => u.Id == oldAccount.Id);
            if (ModelState.IsValid && user.Login != "Administrator") {
                if (Helper.canAccess(User, user.Id)) {
                    while (user.Implementing.Count() > 0) {
                        var issue = user.Implementing.First();
                        issue.ImplementerId = null;
                    }
                    db.SaveChanges();
                    while (user.Assigned.Count() > 0) {
                        var issue = user.Assigned.First();
                        issue.AssignerId = null;
                    }
                    db.SaveChanges();
                    user.Projects.Clear();
                    user.OwnedProjects.Clear();
                    db.Users.DeleteObject(user);
                    db.SaveChanges();
                    Membership.DeleteUser(user.Login, true);
                }
                return RedirectToAction("Index");
            } else {
                return View("Index");
            }
        }

        // GET: /User/Edit/
        [Authorize]
        public ActionResult Edit(int id = 0) {
            try {
                var users = db.Users;
                var curUserId = (from i in users where i.Login == User.Identity.Name select i.Id).Single();
                if (User.IsInRole("Administrator") || curUserId == id) {
                    User user = db.Users.Single(u => u.Id == id);
                    return View(user);
                } else {
                    return RedirectToAction("Index");
                }
            }
            catch (Exception e) {
                return RedirectToAction("Error");
            }

        }

        //
        // POST: /User/Edit/

        [HttpPost]
        public ActionResult Edit(User user) {
            if (ModelState.IsValid) {
                try {
                    User target = db.Users.Single(u => u.Id == user.Id);
                    target.Name = user.Name;
                    db.Users.ApplyCurrentValues(target);

                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception e) {
                    return RedirectToAction("Error");
                }
            }

            return View(user);
        }

        // GET: /User/Edit/
        [Authorize]
        public ActionResult Details(User user) {
            if (User.IsInRole("Administrator") || User.Identity.Name == user.Login) {
                return View(user);
            } else {
                return RedirectToAction("Index");
            }
        }

    }
}
